<?php

/*
	Check if a session user id exist or not. If not set redirect
	to login page. If the user session id exist and there's found
	$_GET['logout'] in the query string logout the user
*/
function checkUser()
{
	// if the session id is not set, redirect to login page
	if (!isset($_SESSION['ql_ctnckh_user_id'])) {
		//echo 'Location: ' . WEB_ROOT . 'admin/login.php';
		//header('Location: http://localhost/website_CSDL_KHCN_maychong/admin/login.php');
		header('Location: ' . WEB_ROOT . 'admin/login.php');
		exit;
	}
	
	// the user want to logout
	if (isset($_GET['logout'])) {
		doLogout();
	}
}

function strtolowertr($metin){ 
    return mb_convert_case(str_replace('I','ı',$metin), MB_CASE_LOWER, "UTF-8"); 
} 

function strtouppertr($metin){ 
    return mb_convert_case(str_replace('i','İ',$metin), MB_CASE_UPPER, "UTF-8"); 
} 

function ucwordstr($metin) { 
    return ltrim(mb_convert_case(str_replace(array(' I',' ı', ' İ', ' i'),array(' I',' I',' İ',' İ'),' '.$metin), MB_CASE_TITLE, "UTF-8")); 
} 

function ucfirsttr($metin) { 
		$metin = in_array(crc32($metin[0]),array(1309403428, -797999993, 957143474)) ? array(strtouppertr(substr($metin,0,2)),substr($metin,2)) : array(strtouppertr($metin[0]),	substr($metin,1)); 
	return $metin[0].$metin[1]; 
} 

function shortName($str1='', $str2 = ''){
	if (strtouppertr($str2) == 'TIẾN SĨ') {
		if (strtouppertr($str1) == 'PHÓ GIÁO SƯ') {return 'PGS.TS. ';}
		else if (strtouppertr($str1) == 'GIÁO SƯ') {return 'GS.TS. ';}
	}
	else if (strtouppertr($str2) == 'THẠC SỸ') return 'ThS. ';
}

function doLogin()
{
	// if we found an error save the error message in this variable
	$errorMessage = '';
	
	$userName = $_POST['txtUserName'];
	$password = $_POST['txtPassword'];
	
	// first, make sure the username & password are not empty
	if ($userName == '') {
		$errorMessage = 'You must enter your username';
	} else if ($password == '') {
		$errorMessage = 'You must enter the password';
	} else {
		// check the database and see if the username and password combo do match
		$sql = "SELECT user_id
		        FROM users 
				WHERE user_name = '$userName' AND user_password = '$password'";
		$result = dbQuery($sql);
	
		if (dbNumRows($result) == 1) {
			$row = dbFetchAssoc($result);
			$_SESSION['ql_ctnckh_user_id'] = $row['user_id'];
			
			// log the time when the user last login
			$sql = "UPDATE users
			        SET user_last_login = NOW() 
					WHERE user_id = '{$row['user_id']}'";
			dbQuery($sql);

			// now that the user is verified we move on to the next page
            // if the user had been in the admin pages before we move to
			// the last page visited
			if (isset($_SESSION['login_return_url'])) {
				header('Location: ' . $_SESSION['login_return_url']);
				exit;
			} else {
				header('Location: index.php');
				exit;
			}
		} else {
			$errorMessage = 'Wrong username or password';
		}		
			
	}
	
	return $errorMessage;
}

/*
	Logout a user
*/
function doLogout()
{
	if (isset($_SESSION['ql_ctnckh_user_id'])) {
		unset($_SESSION['ql_ctnckh_user_id']);
		session_unregister('ql_ctnckh_user_id');
	}
		
	header('Location: login.php');
	exit;
}


/*
	Generate combo box options containing the categories we have.
	if $catId is set then that category is selected
*/

function buildGroupOptions($nhomnc_id = 0)
{
	$sql = "SELECT id, tennnc
			FROM nhomnc
			ORDER BY id";
	$result = dbQuery($sql) or die('Cannot get Author Group. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $nhomnc_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}

function buildTopicGroupOptions($nn_id = 0)
{
	$sql = "SELECT id, tennn
			FROM nhomnganh
			ORDER BY id";
	$result = dbQuery($sql) or die('Cannot get Topic Group. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $nn_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}

function buildDeptOptions($dv_id = 0)
{
	$sql = "SELECT id, tendv
			FROM donvi
			ORDER BY id";
	$result = dbQuery($sql) or die('Không lấy được đơn vị. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $dv_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
function buildLevelOptions($lv_id = 0)
{
	$sql = "SELECT id, tencap
			FROM capthuchien
			ORDER BY id desc";
	$result = dbQuery($sql) or die('Không lấy được cấp thực hiện đề tài. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $lv_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
function buildStyleTopicOptions($loaidt_id = 0)
{
	$sql = "SELECT id, tenloai
			FROM loaidetai
			ORDER BY id desc";
	$result = dbQuery($sql) or die('Không lấy được các loại đề tài. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $loaidt_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
function buildYearOptions($namth = 0)
{
	$sql = "SELECT distinct namthuchien
			FROM detai
			ORDER BY namthuchien desc";
	$result = dbQuery($sql) or die('Không lấy được năm thực hiện đề tài. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($name) = $row;
		$list .= "<option value=\"$name\"";
			if ($name == $namth) {
				$list.= " selected";
			}
			$name2 = $name + 1;
			$list .= ">$name-$name2</option>\r\n";
	}	
	return $list;
	
}
function buildYearOptions1($namth = 0)
{
	$sql = "SELECT distinct namthuchien
			FROM detai
			ORDER BY namthuchien desc";
	$result = dbQuery($sql) or die('Không lấy được năm thực hiện đề tài. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($name) = $row;
		$list .= "<option value=\"$name\"";
			if ($name == $namth) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
	
}
function buildRoleOptions($vt_id = 0)
{
	$sql = "SELECT id, tenvt
			FROM vaitro
			ORDER BY tenvt asc";
	$result = dbQuery($sql) or die('Không lấy được các vai trò. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $vt_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}

function buildPersonOptions($dv_id = 0, $pe_id = 0)
{
	$sql = "SELECT id, hotentg
			FROM tacgia
			WHERE dv_id = $dv_id";
	$result = dbQuery($sql) or die('Không lấy được các tác giả trong đơn vị này. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $pe_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
function buildStateOptions($tt_id = 0)
{
	$sql = "SELECT id, tentt
			FROM trangthai
			ORDER BY id desc";
	$result = dbQuery($sql) or die('Không lấy được trạng thái. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $tt_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}

function buildSchoolOptions($truong_id = 0)
{
	$sql = "SELECT id, tendv
			FROM donvi WHERE truong_id is NULL
			ORDER BY id desc";
	$result = dbQuery($sql) or die('Không lấy được thông tin của trường. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name, $quocgia) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $truong_id) {
				$list.= " selected";
			}
			$chuoi = $name.', '.$tentp;
			$list .= ">$chuoi</option>\r\n";
	}	
	return $list;
}
function buildStyleOptions($khoi_id = 0)
{
	$sql = "SELECT id, tenkhoi
			FROM khoi
			ORDER BY id";
	$result = dbQuery($sql) or die('Không lấy được thông tin của khối. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $khoi_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
//buil branch option use in book
function buildBranchOptions($nganh_id = 0)
{
	$sql = "SELECT id, tennganh
			FROM nganh
			ORDER BY id";
	$result = dbQuery($sql) or die('Không lấy được thông tin của ngành. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $nganh_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}

function buildStyleSeminarOptions($loaiht_id = 0)
{
	$sql = "SELECT id, tenloai
			FROM loaihoithao
			ORDER BY id";
	$result = dbQuery($sql) or die('Không lấy được thông tin loại hội thảo. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $loaiht_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
function buildCountryOptions($qg_id = 0)
{
	$sql = "SELECT id, tenqg
			FROM quocgia
			ORDER BY id";
	$result = dbQuery($sql) or die('Không lấy được thông tin quốc gia. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($dv_id !=0) {
				if ($id == $dv_id) {
					$list.= " selected";
				}
			}
			else if ($id == 151){
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}		
	return $list;
}
//tạo đặc trưng đề tài
function buildPropertyOptions($dtr_id = 0)
{
	$sql = "SELECT id, tendtr
			FROM dactrung_detai
			ORDER BY id";
	$result = dbQuery($sql) or die('Không lấy được thông tin. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $dtr_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
function buildJournalOptions($tc_id = 0)
{
	$sql = "SELECT id, tentc
			FROM tapchi
			ORDER BY id";
	$result = dbQuery($sql) or die('Không lấy được thông tin. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $tc_id) {
				$list.= " selected";
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
function buildJournalStyleOptions($loaitc_id = 0)
{
	$sql = "SELECT id, tenloai
			FROM loaitapchi
			ORDER BY id";
	$result = dbQuery($sql) or die('Không lấy được thông tin. ' . mysql_error());
	
	$groups = array();
	$list = '';
	while($row = dbFetchArray($result)) {
		list($id, $name) = $row;
		$list .= "<option value=\"$id\"";
			if ($id == $loaitc_id) {
				$list.= " selected";
			}
			if (substr($name, 0, 1) != "K") {
				$name = "Tạp chí ".$name;
			}
			$list .= ">$name</option>\r\n";
	}	
	return $list;
}
/*
	Create a thumbnail of $srcFile and save it to $destFile.
	The thumbnail will be $width pixels.
*/
function createThumbnail($srcFile, $destFile, $width, $quality = 75)
{
	$thumbnail = '';
	
	if (file_exists($srcFile)  && isset($destFile))
	{
		$size        = getimagesize($srcFile);
		$w           = number_format($width, 0, ',', '');
		$h           = number_format(($size[1] / $size[0]) * $width, 0, ',', '');
		
		$thumbnail =  copyImage($srcFile, $destFile, $w, $h, $quality);
	}
	
	// return the thumbnail file name on sucess or blank on fail
	return basename($thumbnail);
}

/*
	Copy an image to a destination file. The destination
	image size will be $w X $h pixels
*/
function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
{
    $tmpSrc     = pathinfo(strtolower($srcFile));
    $tmpDest    = pathinfo(strtolower($destFile));
    $size       = getimagesize($srcFile);

    if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
    {
       $destFile  = substr_replace($destFile, 'jpg', -3);
       $dest      = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } elseif ($tmpDest['extension'] == "png") {
       $dest = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } else {
      return false;
    }

    switch($size[2])
    {
       case 1:       //GIF
           $src = imagecreatefromgif($srcFile);
           break;
       case 2:       //JPEG
           $src = imagecreatefromjpeg($srcFile);
           break;
       case 3:       //PNG
           $src = imagecreatefrompng($srcFile);
           break;
       default:
           return false;
           break;
    }

    imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

    switch($size[2])
    {
       case 1:
       case 2:
           imagejpeg($dest,$destFile, $quality);
           break;
       case 3:
           imagepng($dest,$destFile);
    }
    return $destFile;

}

/*
	Create the paging links
*/
function getPagingNav($sql, $pageNum, $rowsPerPage, $queryString = '')
{
	$result  = mysql_query($sql) or die('Error, query failed. ' . mysql_error());
	$row     = mysql_fetch_array($result, MYSQL_ASSOC);
	$numrows = $row['numrows'];
	
	// how many pages we have when using paging?
	$maxPage = ceil($numrows/$rowsPerPage);
	
	$self = $_SERVER['PHP_SELF'];
	
	// creating 'previous' and 'next' link
	// plus 'first page' and 'last page' link
	
	// print 'previous' link only if we're not
	// on page one
	if ($pageNum > 1)
	{
		$page = $pageNum - 1;
		$prev = " <a href=\"$self?page=$page{$queryString}\">[Prev]</a> ";
	
		$first = " <a href=\"$self?page=1{$queryString}\">[First Page]</a> ";
	}
	else
	{
		$prev  = ' [Prev] ';       // we're on page one, don't enable 'previous' link
		$first = ' [First Page] '; // nor 'first page' link
	}
	
	// print 'next' link only if we're not
	// on the last page
	if ($pageNum < $maxPage)
	{
		$page = $pageNum + 1;
		$next = " <a href=\"$self?page=$page{$queryString}\">[Next]</a> ";
	
		$last = " <a href=\"$self?page=$maxPage{$queryString}{$queryString}\">[Last Page]</a> ";
	}
	else
	{
		$next = ' [Next] ';      // we're on the last page, don't enable 'next' link
		$last = ' [Last Page] '; // nor 'last page' link
	}
	
	// return the page navigation link
	return $first . $prev . " Showing page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last; 
}
function get_sum_count($sql){
//var_dump($sql);
//die();
$result = dbQuery($sql);
$row  = dbFetchAssoc($result);
$set_dem = 0;
if ($row) {
        extract($row);
if(isset($sum_count))
$set_dem = $sum_count;
}
return $set_dem;
}
?>